 
import os, sys  
  
sys.path.insert(0, "C:\Documents and Settings\wendy_admin\src\eclipse_workspace\djangodb\main")  
if not os.environ.has_key("DJANGO_SETTINGS_MODULE"):
    os.environ["DJANGO_SETTINGS_MODULE"]="wjContact.settings"
    

import datetime

from django import newforms as forms
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import redirect_to_login
from django.core.paginator import ObjectPaginator

from wjContact.contacts.constants import MSG_CODES, DEFAULT_LISTSIZE

from wjContact.contacts.models import Phone, ContactPhone
from wjContact.contacts.models import Contact, Recipient, Volunteer
#from wjContact.contacts.models import GroupService, Group


from wjContact.sales.models import Sale
#from wjContact.computers.models import Computer

from wjContact.contacts.views.forms import *

import pdb


def ajax_suburb_autocomplete(request):
  if request.GET.has_key('q'):
    suburbs = PCSuburb.objects.filter(name__istartswith=request.GET['q'])[:10]
    return HttpResponse('\n'.join(suburb.name for suburb in suburbs))

  return HttpResponse()  

##============================================================================##
## Pagination tools - currently used by the search view, probably eventually to 
## be used by the index view and any other generally 'list-ey' types of views.
## Nicked from 
## http://hotoss.googlecode.com/svn/trunk/bookmark/constants.py 
## ===========================================================================##

def paginator_dic(paginator, page, page_url):
    d = {}
    d['is_paginated'] = paginator.pages > 1
    d['has_next'] = paginator.has_next_page(page)
    d['has_previous'] = paginator.has_previous_page(page)
    d['next'] = page + 1
    d['previous'] = page - 1
    d['currentpage'] = page+1
    d['totalpages'] = paginator.pages
    d['lastpage'] = paginator.pages - 1
    d['page_url'] = page_url
    return d

## Nicked from 
## http://hotoss.googlecode.com/svn/trunk/bookmark/constants.py
def get_listsize(user):
    if user.is_anonymous():
        listsize = DEFAULT_LISTSIZE
    else:
        # to be implemented 'later' :)
        #listsize = user.get_profile().listsize
        listsize = DEFAULT_LISTSIZE
    return listsize

##============================================================================##
## Some general-utility views - logout, and underConstruction 
## ===========================================================================##    
def logout(request, next_page=None, template_name='accounts/logged_out.html'):
    from django.contrib.auth.views import logout
    return logout(request, next_page=None, template_name=template_name)  
    
def underConstruction(request):
    """ This view just throws out the 'under construction' page. """
    return render_to_response('under_construction.html', 
                              context_instance=RequestContext(request))

##============================================================================##
## Probably deprecated methods - here only until their replacements are fully 
## finished
## ===========================================================================##


##============================================================================##
## Methods for cbv-users
## ===========================================================================##
def viewProfile(request):
    """
    View a cbv-staff-user's personalised settings. At the moment this view does 
    nothing much, as users have no personalised settings, but once they do, 
    they can view and change them here :)  Personalised settings are things 
    like which style sheet to use and how many results to show on the 
    search page.
    """
    return render_to_response('accounts/profile.html', 
        context_instance=RequestContext(request))
    
##============================================================================##
## Index and Search views
## ===========================================================================##    
        
def indexContact(request):
    """ List all contacts."""
    contacts = Contact.objects.all().order_by('last_name')
    return render_to_response(
        'index.html', 
        {'contact_list': contacts},
        context_instance=RequestContext(request))

## The following code is based on code from the open-source 
## 'Hotoss' project. <licensing> 
## From http://hotoss.googlecode.com/svn/trunk/bookmark/views.py
def search(request):
#    if not query:
#            return HttpResponseRedirect('/')
    if not request.GET.items():
        #return HttpResponseRedirect('/contacts/add/')
        ## 1. display a search form - built from the Contact model. This is just
        ## an "unbound" ContactForm.
        ContactForm = forms.form_for_model(Contact)
        search_form = ContactForm()
        return render_to_response('search.html', 
            {'search_form' : search_form},
            context_instance=RequestContext(request))  
    ## 1. display a search form - built from the Contact model. This is just
    ## an "unbound" ContactForm.
    ContactForm = forms.form_for_model(Contact)
    search_form = ContactForm(request.GET)
    ## For searching, not all fields are required.  
    for field in search_form.fields.values():  
        field.required = False 
    ## No point searching on invalid entries, so check validity first.        
    if search_form.is_valid():
        fname = search_form.clean()['first_name']
        results = Contact.objects.filter(first_name__icontains=fname)
        ## List results.
        paginator = ObjectPaginator(results , get_listsize(request.user))
        page = int(request.GET.get('page', 0))
        msg = int(request.GET.get('msg', 0))
        if paginator.pages:
            single_page_of_results = paginator.get_page(page)
        else:
            results = []
        abs_url = '/contacts/search/'
        d = {'msg': MSG_CODES.get(msg,''), 
             'search_results': single_page_of_results, 
             'abs_url': abs_url }
    ## We will also be rendering a new, empty search form for them to 
    ## search again. Get this ready now.
    new_empty_search_form = ContactForm()
    d.update(paginator_dic(paginator, page, abs_url))
    d.update({'search_form': new_empty_search_form })
    context = RequestContext(request, d)
    return render_to_response('search.html', context)  
searchContactForm = login_required(search)     
        

##============================================================================##
## Methods and views which user multi-table forms
##============================================================================##


def owner_edit(request, main_object_id=None):
    return owner(request, main_object_id=main_object_id)
    
def owner(request, main_object_id=None):
    """ """
    ## See contrib/admin/views.main.add_stage() for some ideas...   
    ## If user has hit the submit button, the request method will be 'POST'...
    #pdb.set_trace()
    if request.method == 'POST':
        ## The following works whether we are an adding form or an editing
        ## form.
        for key in request.POST.keys():
            ## The key should be 'add_another_pet', 'add_another_phone', etc
            if key.startswith('add_another'):
                base_name = key.split('_')[2]
                plural_name = base_name + 's'
                request_data = dict(request.POST)
                new_request_data = {}
                for key in request_data:
                    new_request_data[key] = request_data[key][0]   
                if main_object_id:
                    ## we are editing.      
                    object = Owner.objects.get(pk=main_object_id)                 
                    filled_form = OwnerForm(initial=new_request_data, main_object=object)
                else:
                    ## we are adding.
                    filled_form = OwnerForm(initial=new_request_data)
                    
                filled_form.__getattribute__(plural_name).add_fields(1)
                filled_form.put_fieldlists_into_form_fields()
                #pdb.set_trace()        
                ff=filled_form
                #pdb.set_trace()
                msg = "Here are the additional pet-entry fields you asked for..."
                request.user.message_set.create(message=msg)
                return render_to_response(
                  'owner.html', 
                  {'form' : filled_form},
                  context_instance=RequestContext(request)
                  )          
        if main_object_id:
            ## We are an editing form
            object = Owner.objects.get(pk=main_object_id)  
            filled_form =  OwnerForm(request.POST, main_object=object)
        else:
             ## We are an adding form       
            filled_form = OwnerForm(request.POST)
        ## handle_owner_form does validation and re-rendering or directing on. 
        ff=filled_form
        #pdb.set_trace()                  
        return handle_owner_form(request, filled_form)   
    ## If request.method is not 'POST', then the user has not yet hit the 
    ## submit button  -->  render an empty form for them to fill in ...       
    else:  
        if main_object_id:   
            #pdb.set_trace() 
            object = Owner.objects.get(pk=main_object_id)
            empty_form = OwnerForm(main_object=object)
#            emf=empty_form 
#            pdb.set_trace() 
            form_instructions = "Edit an existing Pet-Owner here!"
        else:
            empty_form = OwnerForm()
            form_instructions = "Add a new Pet-Owner here!"
    ef=empty_form
    #pdb.set_trace()      
    return render_to_response(
        'owner.html', 
        {
         'form' : empty_form,
         'form_instructions': form_instructions,
         },
        context_instance=RequestContext(request)
        )                                     
owner = login_required(owner) 

def handle_owner_form(request, filled_form): 
    """
    Check that the filled form is valid, and check for duplicates. 
    
     1. If everything checks out ok: get the form to save() itself and return
        the 'save and redirect' method.
     2. If there are duplicates, instead render a page listing these.
     3. If the form data is invalid in some way, re-render the form with the
        error messages displayed, so that the user can fix them.
     """
    ff = filled_form
    #pdb.set_trace()
    if not (filled_form.is_valid()):
        #pdb.set_trace()
        ## If it's not valid, render failure message
        msg = "Couldn't add new contact using the details given. Please fix the problems listed below and I'll try again :)"
        request.user.message_set.create(message=msg)
        return render_to_response('owner.html',
             {'form': filled_form}, 
             context_instance=RequestContext(request) )  
    ## Check that this entry does not duplicate an existing one...
    ## The check_for_duplicates() method returns either an appropriate
    ## response object, which is 'True', and we pass it on, or else it 
    ## returns None. Should consider refactoring
    ## this, to keep views type stuff out of the file.
    ## Only check for duplicates if we are adding a new entry, not if we are
    ## updating an existing one.
    
    saver = save_and_redirect2(request, filled_form)
    ## And if there are no duplicates, save the data from this form 
    ## to the database, and redirect to the list of all existing 
    ## contacts. Always return an HttpResponseRedirect after 
    ## successfully dealing with POST data. This prevents data from 
    ## being posted twice if a user hits the Back button. 
    return saver

def owner_list(request):
    """ List all Pet-Owners."""
    owners = Owner.objects.all().order_by('last_name')
    return render_to_response(
        'owner_list.html', 
        {'owner_list': owners},
        context_instance=RequestContext(request))    
    
   

################################################################################


################################################################################

def recipient_edit(request, main_object_id=None):
    return recipient(request, main_object_id=main_object_id)
    
def recipient(request, main_object_id=None):
    """ """
    ## See contrib/admin/views.main.add_stage() for some ideas...   
    ## If user has hit the submit button, the request method will be 'POST'...
    ## The following works whether we are an adding form or an editing
    ## form.
    if request.method == 'POST':     
        for key in request.POST.keys():
            ## The key should be 'add_another_pet', 'add_another_phone', etc
            if key.startswith('add_another'):
                base_name = key.split('_')[2]
                plural_name = base_name + 's'
                request_data = dict(request.POST)
                new_request_data = {}
                for key in request_data:
                    new_request_data[key] = request_data[key][0]   
                if main_object_id:
                    ## we are editing.      
                    object = Recipient.objects.get(pk=main_object_id)                 
                    filled_form = RecipientForm(initial=new_request_data, main_object=object)
                else:
                    ## we are adding.
                    filled_form = RecipientForm(initial=new_request_data)
                    
                filled_form.__getattribute__(plural_name).add_fields(1)
                filled_form.put_fieldlists_into_form_fields()
                #pdb.set_trace()        
                ff=filled_form
                #pdb.set_trace()
                msg = "Here are the additional entry fields you asked for..."
                request.user.message_set.create(message=msg)
                return render_to_response(
                  'recipient.html', 
                  {'form' : filled_form},
                  context_instance=RequestContext(request)
                  )          
        if main_object_id:
            ## We are an editing form    
            object = Recipient.objects.get(pk=main_object_id)  
            filled_form = RecipientForm(request.POST, main_object=object)
        else:
             ## We are an adding form       
            filled_form = RecipientForm(request.POST)
        ## handle_recipient_form does validation and re-rendering or directing on. 
        ff=filled_form
        #pdb.set_trace()                  
        return handle_recipient_form(request, filled_form)   
    ## If request.method is not 'POST', then the user has not yet hit the 
    ## submit button  -->  render an empty form for them to fill in ...       
    else:  
        if main_object_id:   
            #pdb.set_trace() 
            object = Recipient.objects.get(pk=main_object_id)
            empty_form = RecipientForm(main_object=object)
#            emf=empty_form 
#            pdb.set_trace() 
            form_instructions = "Edit an existing Recipient here!"
        else:
            empty_form = RecipientForm()
            form_instructions = "Add Recipient details here!"
    ef=empty_form   
    return render_to_response(
        'recipient.html', 
        {
         'form' : empty_form,
         'form_instructions': form_instructions,
         },
        context_instance=RequestContext(request)
        )                                     
recipient = login_required(recipient) 

def handle_recipient_form(request, filled_form): 
    """
    Check that the filled form is valid, and check for duplicates. 
    
     1. If everything checks out ok: get the form to save() itself and return
        the 'save and redirect' method.
     2. If there are duplicates, instead render a page listing these.
     3. If the form data is invalid in some way, re-render the form with the
        error messages displayed, so that the user can fix them.
     """
    if not (filled_form.is_valid()):
        #pdb.set_trace()
        ## If it's not valid, render failure message
        msg = "Couldn't add new recipient using the details given. Please fix the problems listed below and I'll try again :)"
        request.user.message_set.create(message=msg)
        return render_to_response('recipient.html',
             {'form': filled_form}, 
             context_instance=RequestContext(request) )  
    ## Check that this entry does not duplicate an existing one...
    ## The check_for_duplicates() method returns either an appropriate
    ## response object, which is 'True', and we pass it on, or else it 
    ## returns None. Should consider refactoring
    ## this, to keep views type stuff out of the file.
    ## Only check for duplicates if we are adding a new entry, not if we are
    ## updating an existing one.
    recipient = filled_form.save()
    fname = filled_form.clean_data['first_name']
    lname = filled_form.clean_data['last_name']
    msg = "New recipient %s %s successfully added." % (fname, lname)
    request.user.message_set.create(message=msg)
    if 'add_and_continue' in request.POST.keys():
        #return sale_edit(request, recipient_id=recipient.id)   
        #post_url_continue='../%s/'
        post_url_continue="http://localhost:8000/recipient/%s/sales_add/"
        return HttpResponseRedirect(post_url_continue % recipient.id)
        #return HttpResponseRedirect(post_url_continue % pk_value)
    else:   
        redirect_to = "http://localhost:8000/contacts/recipients"
        return HttpResponseRedirect(redirect_to)  
        
#    saver = save_and_redirect(request, filled_form, redirect_to)
#    ## And if there are no duplicates, save the data from this form 
#    ## to the database, and redirect to the list of all existing 
#    ## recipients. Always return an HttpResponseRedirect after 
#    ## successfully dealing with POST data. This prevents data from 
#    ## being posted twice if a user hits the Back button. 
#    return saver


def sales_list(request):
    """ List all sales."""
    sales = Sale.objects.all()
    return render_to_response(
        'sales_list.html', 
        {'sales_list': sales},
        context_instance=RequestContext(request))    
     
def sales_edit(request, main_object_id=None, recipient_id=None, computer_id=None):
    ## <wsl> FIXME: may want to get rid of main_object_id if it is unused.
    if recipient_id:
        return  sale_to_recipient(request, recipient_id=recipient_id)
    
def sale_to_recipient(request,  recipient_id=None):
    """ """
    ## See contrib/admin/views.main.add_stage() for some ideas...   
    ## If user has hit the submit button, the request method will be 'POST'...
    ## The following works whether we are an adding form or an editing
    ## form.
    if request.method == 'POST':    
        ## We are an adding form       
        form = SalesForm(request.POST)
        ## handle_recipient_form does validation and re-rendering or directing on.               
        return handle_sales_form(request, form)          
    else:  
        ## Make an empty form with just the recipient_id set (using the initial 
        ## keyword)
        form = SalesForm(initial = {'recipient': recipient_id})
        form_instructions = "Add a new sale to recipient %s  here!" % recipient_id
        return render_to_response(
            'sales.html', 
            {
            'form' : form,
            'form_instructions': form_instructions,
            },
            context_instance=RequestContext(request)
            )                                     
sale_to_recipient = login_required(sale_to_recipient) 

def handle_sales_form(request, filled_form): 
    """
    Check that the filled form is valid, and check for duplicates. 
    
     1. If everything checks out ok: get the form to save() itself and return
        the 'save and redirect' method.
     2. If there are duplicates, instead render a page listing these.
     3. If the form data is invalid in some way, re-render the form with the
        error messages displayed, so that the user can fix them.
     """
    if not (filled_form.is_valid()):
        ## If it's not valid, render failure message
        msg = "Couldn't add new sale using the details given. Please fix the problems listed below and I'll try again :)"
        request.user.message_set.create(message=msg)
        return render_to_response('sales.html',
             {'form': filled_form}, 
             context_instance=RequestContext(request) )  
    contact = filled_form.save()
    recipient_id = filled_form.clean_data['recipient']
    computer_id = filled_form.clean_data['computer']
    msg = "Sale of computer %s to recipient %s successfully recorded." % (computer_id, recipient_id)
    request.user.message_set.create(message=msg)
    redirect_to = "http://localhost:8000/sales/"
    return HttpResponseRedirect(redirect_to)  
        

def save_and_redirect(request, form, redirect_to=None, msg='Saved'):
    form.save()
    msg = " %s" % msg
    request.user.message_set.create(message=msg)
    return HttpResponseRedirect(redirect_to)  

def recipient_list(request):
    """ List all recipients."""
    recipients = Recipient.objects.all()
    #recipients = Recipient.objects.all().order_by('contacts_contact.last_name')
    #Entry.objects.order_by('blogs_blog.name', 'headline')
    ##FIXME
    ## Pass in a list of (contact, recipient) tuples. This is because some of 
    ## the attributes we will want to display in the list belong to the contact
    ## object (first_name, address, etc), while some belong to the recipient
    ## object (experience, and so on).   
    contacts_and_recipients = []
    for recipient in recipients:
        contact = Contact.objects.get(id=recipient.contact_id)
        contacts_and_recipients.append((contact, recipient))
    return render_to_response(
        'recipient_list.html', 
        {'contacts_and_recipients_list': contacts_and_recipients},
        context_instance=RequestContext(request))    
     
    
################################################################################

def contact_edit(request, main_object_id=None):
    return contact(request, main_object_id=main_object_id)
    
def contact(request, main_object_id=None):
    """ """
    ## See contrib/admin/views.main.add_stage() for some ideas...   
    ## If user has hit the submit button, the request method will be 'POST'...
    ##pdb.set_trace() ***************
    if request.method == 'POST':
        ## The following works whether we are an adding form or an editing
        ## form.
        for key in request.POST.keys():
            ## The key should be 'add_another_pet', 'add_another_phone', etc
            if key.startswith('add_another'):
                base_name = key.split('_')[2]
                plural_name = base_name + 's'
                request_data = dict(request.POST)
                new_request_data = {}
                for key in request_data:
                    new_request_data[key] = request_data[key][0]   
                if main_object_id:
                    ## we are editing.      
                    object = Contact.objects.get(pk=main_object_id)                 
                    filled_form = ContactForm(initial=new_request_data, main_object=object)
                else:
                    ## we are adding.
                    filled_form = ContactForm(initial=new_request_data)
                    
                filled_form.__getattribute__(plural_name).add_fields(1)
                filled_form.put_fieldlists_into_form_fields()
                #pdb.set_trace()        
                ff=filled_form
                #pdb.set_trace()
                msg = "Here are the additional entry fields you asked for..."
                request.user.message_set.create(message=msg)
                return render_to_response(
                  'contact.html', 
                  {'form' : filled_form},
                  context_instance=RequestContext(request)
                  )          
        if main_object_id:
            ## We are an editing form    
            object = Contact.objects.get(pk=main_object_id)  
            filled_form =  ContactForm(request.POST, main_object=object)
        else:
             ## We are an adding form       
            filled_form = ContactForm(request.POST)
        ## handle_contact_form does validation and re-rendering or directing on. 
        ff=filled_form
        #pdb.set_trace() 
        ##process_form(request, filled_form, template, redirect_to):  
        template = "contact.html"
        redirect_to = "http://localhost:8000/contacts/contacts"
        return process_form(request, filled_form, template, redirect_to)                
        #return handle_contact_form(request, filled_form)   
    ## If request.method is not 'POST', then the user has not yet hit the 
    ## submit button  -->  render an empty form for them to fill in ...       
    else:  
        if main_object_id:   
            #pdb.set_trace() 
            object = Contact.objects.get(pk=main_object_id)
            empty_form = ContactForm(main_object=object)
#            emf=empty_form 
#            pdb.set_trace() 
            form_instructions = "Edit an existing Associate here!"
        else:
            empty_form = ContactForm()
            form_instructions = "Add a new Associate here!"
    ef=empty_form
    #pdb.set_trace()      
    return render_to_response(
        'contact.html', 
        {
         'form' : empty_form,
         'form_instructions': form_instructions,
         },
        context_instance=RequestContext(request)
        )                                     
contact = login_required(contact) 

def handle_contact_form(request, filled_form): 
    """
    Check that the filled form is valid, and check for duplicates. 
    
     1. If everything checks out ok: get the form to save() itself and return
        the 'save and redirect' method.
     2. If there are duplicates, instead render a page listing these.
     3. If the form data is invalid in some way, re-render the form with the
        error messages displayed, so that the user can fix them.
     """
    ff = filled_form
    #pdb.set_trace()
    if not (filled_form.is_valid()):
        #pdb.set_trace()
        ## If it's not valid, render failure message
        msg = "Couldn't add new contact using the details given. Please fix the problems listed below and I'll try again :)"
        request.user.message_set.create(message=msg)
        return render_to_response('contact.html',
             {'form': filled_form}, 
             context_instance=RequestContext(request) )  
    ## Check that this entry does not duplicate an existing one...
    ## The check_for_duplicates() method returns either an appropriate
    ## response object, which is 'True', and we pass it on, or else it 
    ## returns None. Should consider refactoring
    ## this, to keep views type stuff out of the file.
    ## Only check for duplicates if we are adding a new entry, not if we are
    ## updating an existing one.
    
    saver = save_and_redirect3(request, filled_form)
    ## And if there are no duplicates, save the data from this form 
    ## to the database, and redirect to the list of all existing 
    ## contacts. Always return an HttpResponseRedirect after 
    ## successfully dealing with POST data. This prevents data from 
    ## being posted twice if a user hits the Back button. 
    return saver
 
def contact_list(request):
    """ List all Contacts."""
    contacts = Contact.objects.all().order_by('last_name')
    return render_to_response(
        'contact_list.html', 
        {'contact_list': contacts},
        context_instance=RequestContext(request))    
    
   
#==============================================================================#

def process_form(request, filled_form, template, redirect_to): 
    """
    Check that the filled form is valid, and check for duplicates. 
    
     1. If everything checks out ok: get the form to save() itself and return
        the 'save and redirect' method.
     2. If there are duplicates, instead render a page listing these.
     3. If the form data is invalid in some way, re-render the form with the
        error messages displayed, so that the user can fix them.
     """
    ff = filled_form
    #pdb.set_trace()
    if not (filled_form.is_valid()):
        #pdb.set_trace()
        ## If it's not valid, render failure message
        msg = "Couldn't add new %s using the details given. Please fix the problems listed below and I'll try again. " % filled_form.main_object
        request.user.message_set.create(message=msg)
        return render_to_response(template,
             {'form': filled_form}, 
             context_instance=RequestContext(request) )  
    ## TODO:  Check that this entry does not duplicate an existing one...
    ## And if there are no duplicates, save the data from this form 
    ## to the database, and redirect to the list of all existing 
    ## contacts. Always return an HttpResponseRedirect after 
    ## successfully dealing with POST data. This prevents data from 
    ## being posted twice if a user hits the Back button. 
    msg = "New %s successfully added." % (filled_form.klass.__name__)
    return save_and_redirect(request, filled_form, redirect_to=redirect_to, msg=msg)


def save_and_redirect7(request, form, redirect_to):
    form.save()
    msg = "save_and_redirect7(): New %s successfully added." % (form.klass.__name__)
    request.user.message_set.create(message=msg)
    return HttpResponseRedirect(redirect_to)  
    #return HttpResponseRedirect("http://localhost:8000/contacts/contacts")  
    
#=============================================================================#

#def computer_add(request, main_object_id=None):
#    return computer(request, main_object_id=main_object_id)
#
#def computer_edit(request, main_object_id=None):
#    return computer(request, main_object_id=main_object_id)
    
#def computer(request, main_object_id=None):
#    """ """
#    ## See contrib/admin/views.main.add_stage() for some ideas...   
#    ## If user has hit the submit button, the request method will be 'POST'...
#    ##pdb.set_trace() ***************
#    if request.method == 'POST':
#        ## The following works whether we are an adding form or an editing
#        ## form.
#        for key in request.POST.keys():
#            ## The key should be 'add_another_pet', 'add_another_phone', etc
#            if key.startswith('add_another'):
#                base_name = key.split('_')[2]
#                plural_name = base_name + 's'
#                request_data = dict(request.POST)
#                new_request_data = {}
#                for key in request_data:
#                    new_request_data[key] = request_data[key][0]   
#                if main_object_id:
#                    ## we are editing.      
#                    object = Computer.objects.get(pk=main_object_id)                 
#                    filled_form = ComputerForm(initial=new_request_data, main_object=object)
#                else:
#                    ## we are adding.
#                    filled_form = ComputerForm(initial=new_request_data)
#                    
#                filled_form.__getattribute__(plural_name).add_fields(1)
#                filled_form.put_fieldlists_into_form_fields()
#                #pdb.set_trace()        
#                ff=filled_form
#                #pdb.set_trace()
#                msg = "Here are the additional entry fields you asked for..."
#                request.user.message_set.create(message=msg)
#                return render_to_response(
#                  'computer.html', 
#                  {'form' : filled_form},
#                  context_instance=RequestContext(request)
#                  )          
#        if main_object_id:
#            ## We are an editing form    
#            object = Computer.objects.get(pk=main_object_id)  
#            filled_form =  ComputerForm(request.POST, main_object=object)
#        else:
#             ## We are an adding form       
#            filled_form = ComputerForm(request.POST)
#        ## handle_contact_form does validation and re-rendering or directing on. 
#        ff=filled_form
#        #pdb.set_trace() 
#        ##process_form(request, filled_form, template, redirect_to):  
#        template = "computer.html"
#        redirect_to = "http://localhost:8000/computers"
#        return handle_computer_form(request, filled_form)                
#        #return handle_contact_form(request, filled_form)   
#    ## If request.method is not 'POST', then the user has not yet hit the 
#    ## submit button  -->  render an empty form for them to fill in ...       
#    else:  
#        if main_object_id:   
#            #pdb.set_trace() 
#            object = Computer.objects.get(pk=main_object_id)
#            empty_form = ComputerForm(main_object=object)
##            emf=empty_form 
##            pdb.set_trace() 
#            form_instructions = "Edit an existing Computer here!"
#        else:
#            empty_form = ComputerForm()
#            form_instructions = "Add new Computer here!"
#    ef=empty_form
#    #pdb.set_trace()      
#    return render_to_response(
#        'computer.html', 
#        {
#         'form' : empty_form,
#         'form_instructions': form_instructions,
#         },
#        context_instance=RequestContext(request)
#        )                                     
#computer = login_required(computer) 
#
#def handle_computer_form(request, filled_form): 
#    """
#    Check that the filled form is valid, and check for duplicates. 
#    
#     1. If everything checks out ok: get the form to save() itself and return
#        the 'save and redirect' method.
#     2. If there are duplicates, instead render a page listing these.
#     3. If the form data is invalid in some way, re-render the form with the
#        error messages displayed, so that the user can fix them.
#     """
#    ff = filled_form
#    #pdb.set_trace()
#    if not (filled_form.is_valid()):
#        #pdb.set_trace()
#        ## If it's not valid, render failure message
#        msg = "Couldn't add new computer using the details given. Please fix the problems listed below and I'll try again :)"
#        request.user.message_set.create(message=msg)
#        return render_to_response('computer.html',
#             {'form': filled_form}, 
#             context_instance=RequestContext(request) )  
#    ## Check that this entry does not duplicate an existing one...
#    ## The check_for_duplicates() method returns either an appropriate
#    ## response object, which is 'True', and we pass it on, or else it 
#    ## returns None. Should consider refactoring
#    ## this, to keep views type stuff out of the file.
#    ## Only check for duplicates if we are adding a new entry, not if we are
#    ## updating an existing one.
#    redirect_to = "http://localhost:8000/computers"
#    saver = save_and_redirect(request, filled_form, redirect_to=redirect_to, msg='New Computer succesfully added')
#    ## And if there are no duplicates, save the data from this form 
#    ## to the database, and redirect to the list of all existing 
#    ## contacts. Always return an HttpResponseRedirect after 
#    ## successfully dealing with POST data. This prevents data from 
#    ## being posted twice if a user hits the Back button. 
#    return saver
# 
#def computer_list(request):
#    """ List all Computers."""
#    computers = Computer.objects.all()
#    return render_to_response(
#        'computer_list.html', 
#        {'computer_list': computers},
#        context_instance=RequestContext(request))    
    
   
################################################################################
## Volunteer Views
################################################################################
def volunteer_edit(request, main_object_id=None):
    return volunteer(request, main_object_id=main_object_id)
    
def volunteer(request, main_object_id=None):
    """ """
    ## See contrib/admin/views.main.add_stage() for some ideas...   
    ## If user has hit the submit button, the request method will be 'POST'...
    ##pdb.set_trace() ***************
    if request.method == 'POST':
        ## The following works whether we are an adding form or an editing
        ## form.
        for key in request.POST.keys():
            ## The key should be 'add_another_pet', 'add_another_phone', etc
            if key.startswith('add_another'):
                base_name = key.split('_')[2]
                plural_name = base_name + 's'
                request_data = dict(request.POST)
                new_request_data = {}
                for key in request_data:
                    new_request_data[key] = request_data[key][0]   
                if main_object_id:
                    ## we are editing.      
                    object = Volunteer.objects.get(pk=main_object_id)                 
                    filled_form = VolunteerForm(initial=new_request_data, main_object=object)
                else:
                    ## we are adding.
                    filled_form = VolunteerForm(initial=new_request_data)
                    
                filled_form.__getattribute__(plural_name).add_fields(1)
                filled_form.put_fieldlists_into_form_fields()
                #pdb.set_trace()        
                ff=filled_form
                #pdb.set_trace()
                msg = "Here are the additional entry fields you asked for..."
                request.user.message_set.create(message=msg)
                return render_to_response(
                  'volunteer.html', 
                  {'form' : filled_form},
                  context_instance=RequestContext(request)
                  )          
        if main_object_id:
            ## We are an editing form    
            object = Volunteer.objects.get(pk=main_object_id)  
            filled_form =  VolunteerForm(request.POST, main_object=object)
        else:
             ## We are an adding form       
            filled_form = VolunteerForm(request.POST)
        ## handle_volunteer_form does validation and re-rendering or directing on. 
        ff=filled_form
        #pdb.set_trace() 
        ##process_form(request, filled_form, template, redirect_to):  
        template = "volunteer.html"
        ##<wsl> FIXME
        redirect_to = "http://localhost:8000/contacts/volunteers"
        return process_form(request, filled_form, template, redirect_to)                
        #return handle_volunteer_form(request, filled_form)   
    ## If request.method is not 'POST', then the user has not yet hit the 
    ## submit button  -->  render an empty form for them to fill in ...       
    else:  
        if main_object_id:   
            #pdb.set_trace() 
            object = Volunteer.objects.get(pk=main_object_id)
            empty_form = VolunteerForm(main_object=object)
#            emf=empty_form 
#            pdb.set_trace() 
            form_instructions = "Edit an existing Volunteer here!"
        else:
            empty_form = VolunteerForm()
            form_instructions = "Add Volunteer details here!"
    ef=empty_form
    #pdb.set_trace()      
    return render_to_response(
        'volunteer.html', 
        {
         'form' : empty_form,
         'form_instructions': form_instructions,
         },
        context_instance=RequestContext(request)
        )                                     
volunteer = login_required(volunteer) 

def handle_volunteer_form(request, filled_form): 
    """
    Check that the filled form is valid, and check for duplicates. 
    
     1. If everything checks out ok: get the form to save() itself and return
        the 'save and redirect' method.
     2. If there are duplicates, instead render a page listing these.
     3. If the form data is invalid in some way, re-render the form with the
        error messages displayed, so that the user can fix them.
     """
    ff = filled_form
    #pdb.set_trace()
    if not (filled_form.is_valid()):
        #pdb.set_trace()
        ## If it's not valid, render failure message
        msg = "Couldn't add new volunteer using the details given. Please fix the problems listed below and I'll try again :)"
        request.user.message_set.create(message=msg)
        return render_to_response('volunteer.html',
             {'form': filled_form}, 
             context_instance=RequestContext(request) )  
    ## Check that this entry does not duplicate an existing one...
    ## The check_for_duplicates() method returns either an appropriate
    ## response object, which is 'True', and we pass it on, or else it 
    ## returns None. Should consider refactoring
    ## this, to keep views type stuff out of the file.
    ## Only check for duplicates if we are adding a new entry, not if we are
    ## updating an existing one.
    
    saver = save_and_redirect3(request, filled_form)
    ## And if there are no duplicates, save the data from this form 
    ## to the database, and redirect to the list of all existing 
    ## volunteers. Always return an HttpResponseRedirect after 
    ## successfully dealing with POST data. This prevents data from 
    ## being posted twice if a user hits the Back button. 
    return saver
 
def volunteer_list(request):
    """ List all Volunteers."""
    ##FIXME
    ## Pass in a list of (contact, volunteer) tuples. This is because some of 
    ## the attributes we will want to display in the list belong to the contact
    ## object (first_name, address, etc), while some belong to the volunteer
    ## object (interests, and so on).
    volunteers = Volunteer.objects.all()
    contacts_and_volunteers = []
    for volunteer in volunteers:
        contact = Contact.objects.get(id=volunteer.contact_id)
        contacts_and_volunteers.append((contact, volunteer))
    return render_to_response(
        'volunteer_list.html', 
        {'contacts_and_volunteers_list': contacts_and_volunteers},
        context_instance=RequestContext(request))    
    
   
#==============================================================================#
  
   
